package com.youxin.foundation.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式工具类
 * @author yingde.cao
 *
 */
public class RegexUtils {
	/**
	 * 匹配
	 * @param regex 正则表达式
	 * @param source 源
	 * @param flag 是否忽略大小写
	 * @return boolean 是否切尔西
	 */
	public static boolean match(String regex,String source,int flag)
	{
	    Pattern pattern = Pattern.compile(regex, flag);
	    Matcher matcher = pattern.matcher(source);
	    return matcher.matches();	    
	}
	
	public static boolean match(String regex,String source)
	{
	    return match(regex, source, 0);    
	}
	
	public static <T> T match(String regex,String source,int flag,RegexStatment<T> regexStatment)
	{
	    Pattern pattern = Pattern.compile(regex, flag);
	    Matcher matcher = pattern.matcher(source);
	    boolean success=matcher.matches();
	    return regexStatment.execute(matcher, success);
	}
	
	public static <T> T match(String regex,String source,RegexStatment<T> regexStatment)
	{
	   return match(regex, source, 0, regexStatment);
	}
	
	public static boolean isPhoneNumber(String input){  
		if(StringUtils.isNullOrEmpty(input))
		{
			return false;
		}
	    String regex="1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}";  
	    Pattern p = Pattern.compile(regex);  
	    Matcher matcher=p.matcher(input);
	    return matcher.find();
	}  
	
	public static boolean isTelphone(String input){  
		if(StringUtils.isNullOrEmpty(input))
		{
			return false;
		}
	    String regex="^\\(?[0-9]+\\)?-?\\)?[0-9]{7,8}$";  
	    Pattern p = Pattern.compile(regex);  
	    Matcher matcher=p.matcher(input);
	    return matcher.find();
	}  	
	
	/**
	 * 是否电话号码
	 * @param input
	 * @return
	 */
	public static boolean isMobile(String input){  
		if(StringUtils.isNullOrEmpty(input))
		{
			return false;
		}
	    String regex="^1[\\d]{10}$";  
	    Pattern p = Pattern.compile(regex);  
	    Matcher matcher=p.matcher(input);
	    return matcher.find();
	}  
	
	public static boolean isEmail(String input){  
		if(StringUtils.isNullOrEmpty(input))
		{
			return false;
		}
	    String regex="^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$";  
	    Pattern p = Pattern.compile(regex);  
	    Matcher matcher=p.matcher(input);
	    return matcher.find();
	} 
	
	@FunctionalInterface
	public interface RegexStatment<T>
	{
		/**
		 * 执行匹配访求
		 * @param matcher Matcher
		 * @param success 是否成功
		 * @return
		 */
		public T execute(Matcher matcher,boolean success);
	}
}
